from datetime import datetime

from flask import Blueprint, request, current_app
import pymysql, traceback

from utilsapp.common import parsing_data_id, assign_value

import utilsapp.excel_util
from utilsapp import utils
import time, os, uuid
from utilsapp.mysql_con import (
    db_connect,
    db_delete,
    db_insert,
    db_list,
    db_table_list,
    db_fetchone,
    db_update,
    get_sensor_new_table,
)
from utilsapp.mysql_con import db_operation, db_pagelist
from utilsapp.common import parsing_permissions

spare = Blueprint("spare", __name__)


def get_conn(db_name=None, dbconfig=None):
    d = current_app.config["settings"]["mysql"]
    db_name = d["dbname"] if db_name is None else db_name
    dbconfig = d if dbconfig is None else dbconfig

    return pymysql.connect(
        host=dbconfig["host"],
        user=dbconfig["user"],
        port=dbconfig["port"],
        password=dbconfig["password"],
        db=db_name,
        charset="utf8",
        connect_timeout=10,
        read_timeout=10,
        write_timeout=10,
    )


@spare.route("/getlist", methods=["POST"])
def get_list():
    a = request.json
    name = assign_value(a, "name")
    # 基础语句
    sql = """SELECT * from spare"""
    # 条件语句
    query = " where 1=1 "
    if name != "":
        query += f" and name like '%{name}%'"
    sql = sql + query + " ORDER BY create_time desc"
    res = db_pagelist(sql, request.json["page"], request.json["size"])
    return res


# 添加传感器
@spare.route("/add", methods=["post"])
def sensor_add():
    res = db_insert("spare", request.json)
    utilsapp.excel_util.create_table(
        [request.json], current_app.config["settings"]["mysql"]
    )
    return res


# 传感器类型——删除
@spare.route("/delete", methods=["POST"])
def sensor_delete():
    id = request.json["id"]
    res = db_delete("spare", f"WHERE id=%s", {"id": id})
    db_delete("warn", f"WHERE sensor_id=%s", {"sensor_id": id})
    utilsapp.excel_util.drop_table(
        [request.json], current_app.config["settings"]["mysql"]
    )
    return res


# 传感器类型——修改
@spare.route("/edit", methods=["POST"])
def sensor_edit():
    id = request.json["id"]
    keys_not_add = ["id"]
    addModel = {
        key: request.json[key] for key in request.json if key not in keys_not_add
    }
    res = db_update("spare", addModel, f"WHERE id=%s", {"id": id})
    utilsapp.excel_util.create_table(
        [request.json], current_app.config["settings"]["mysql"]
    )
    return res
